package com.cx.controller;

import com.cx.pojo.Area;
import com.cx.pojo.City;
import com.cx.pojo.Province;
import com.cx.service.AreaService;
import com.cx.service.CityService;
import com.cx.service.ProvinceService;
import com.cx.service.impl.AreaServiceImpl;
import com.cx.service.impl.CityServiceImpl;
import com.cx.service.impl.ProviceServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ReactInChainServlet",urlPatterns = "/reactinchain")
public class ReactInChainServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");
        Gson gson = new Gson();

        if("province".equals(action)) {
            ProvinceService provinceService = new ProviceServiceImpl();
            List<Province> provinceList = provinceService.selectAll();
            String provinceJson = gson.toJson(provinceList);
            response.getWriter().write(provinceJson);
        } else if("city".equals(action)){
            // 获取前端传过来的省份id
            String proId = request.getParameter("proid");
            CityService cityService = new CityServiceImpl();
            List<City> cities = cityService.selectByProId(proId);
            String cityJson = gson.toJson(cities);
            response.getWriter().write(cityJson);
        } else if("area".equals(action)){
            // 获取城市的id
            String cityId = request.getParameter("cityid");
            AreaService areaService = new AreaServiceImpl();
            List<Area> areas = areaService.selectByCityId(cityId);
            String areaJson = gson.toJson(areas);
            response.getWriter().write(areaJson);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);


    }
}
